<script setup lang="ts">
import {ref, onMounted, type Ref, defineAsyncComponent} from 'vue';
import {type Card, type CardDetailInstance, type CardList} from '@/types/card';
import NavHeader from '@/components/NavHeader.vue';
import NdCardBoard from '@/components/modules/NdCards/index.vue';
import CardItem from '@/components/Card.vue';
import { NdCard } from '@/types/NdCard';
import useCardStore from '@/store/card';
const cardStore = useCardStore();
const fields = {
    card: {
        id: 'cardId',
        order: 'order'
    },
    list: {
        id: 'listId',
        title: 'title',
        order: 'order'
    }
};
const CardDetail = defineAsyncComponent({
    loader: () => import('@/components/CardDetail.vue'),
    onError(err, retry){
        retry();
    }
});
// 卡片详情组件的引用
const cardDetailRef:Ref<CardDetailInstance|null> = ref(null);
/**
 * 处理卡片拖拽结束事件
 * 当用户拖动卡片到新位置时，更新服务器中卡片的列表归属和排序
 * 
 * @param cardId - 被拖拽卡片的唯一标识
 * @param listId - 目标列表的唯一标识
 * @param order - 卡片在列表中的新排序位置
 */
const onCardDragEnd = (cardId: string|number, listId: string|number, order: number) =>{
    fetch(`/api/card/${cardId}`, {
        method: 'PUT',
        headers: {  // 添加请求头
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            listId,
            order
        })
    });
};
/**
 * 处理卡片列表拖拽结束事件
 * 当用户拖动整个卡片列表到新位置时，更新服务器中列表的排序
 * 
 * @param cardListId - 被拖拽列表的唯一标识
 * @param order - 列表在看板中的新排序位置
 */
const onCardListDragEnd = (cardListId: string|number, order: number) => {
    fetch(`/api/cardList/${cardListId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            order
        })
    });
};
/**
 * 创建新卡片
 * 向服务器发送创建请求，成功后更新本地状态并执行回调
 * 
 * @param title - 新卡片的标题
 * @param listId - 卡片所属列表的唯一标识
 * @param callback - 创建成功后的回调函数，用于通知UI更新
 */
const onCreateCard = (title: string, listId: string|number, callback: () => void) => {
    fetch('/api/card', {
        method: 'POST',
        body: JSON.stringify({
            title,
            listId
        }),
        headers: {
            'Content-Type': 'application/json'
        }
    }).then(res => res.json())
        .then((res) => {
            if(res['statusCode'] === 0 && res['data']){
                const data = res['data'];
                const cardList = cardStore.cardLists.find((item) => item[fields.list.id] === listId);
                if(cardList){
                    cardList.cards.push({
                        id: data[fields.card.id],
                        cardId: data[fields.card.id],
                        title: data['title'],
                        order: data[fields.card.order]
                    });
                }
                // 回调通知添加完成
                callback();
            }
        });
};

/**
 * 处理卡片选择事件
 * 当用户点击卡片时，显示卡片详情组件
 * 此方法会触发异步组件的加载（如果尚未加载）
 * 
 * @param card - 被选中的卡片对象
 */
const onCardSelect = (card: NdCard) => {
    cardDetailRef.value?.setCardData(card as Card);
    cardDetailRef.value?.setVisible(true);
};
onMounted(() => {
    fetch('/api/cardList').then((res) => {
        res.json().then((data) => {
            cardStore.setCardLists(data['data'] as Array<CardList>);
        });
    });
    
});

</script>
<template>
	<div class="notice-board-root">
		<nav-header />
		<nd-card-board
			:model-value="cardStore.cardLists"
			:fields="fields"
			@update:model-value="cardlists => cardStore.setCardLists(cardlists as Array<CardList>)"
			@card-list-drag-end="onCardListDragEnd"
			@card-drag-end="onCardDragEnd"
			@select="onCardSelect"
			@create-card="onCreateCard"
		>
			<template #default="{card}">
				<card-item :card="card as Card" />
			</template>
		</nd-card-board>
	</div>
	<component 
		:is="CardDetail" 
		ref="cardDetailRef" 
	/>
</template>